<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <!-- 一线运维工程师表单基本信息 -->
      <div id="基本信息">
        <div class="anthor-info-body">
          <el-row :gutter="40">
            <el-col :span="12">
              <el-form-item label="故障级别" prop="failureLevelCode">
                <el-select v-model="formItem.failureLevelCode" placeholder="请选择故障级别">
                  <el-option v-for="item in availableFailureLevels" :key="item.code" :label="item.text" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否解决" prop="solved">
                <el-select v-model="formItem.solved" placeholder="请选择是否解决">
                  <el-option v-for="item in availableSolveds" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="服务类型" prop="worktypeCode">
                <el-select v-model="formItem.worktypeCode" placeholder="请选择服务类型">
                  <el-option v-for="item in availableWorktypes" :key="item.code" :label="item.text" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" size="mini" icon="el-icon-question" @click="selectKnowledge">查询知识库</el-button>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参与工程师" prop="helperEngineerName">
                <el-input v-model="formItem.helperEngineerName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="故障解决情况" prop="failureSolveSituation">
                <el-input v-model="formItem.failureSolveSituation" placeholder="请输入故障解决情况" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" />
              </el-form-item>
            </el-col>
          </el-row>

        </div>
      </div>
      <!-- 资产列表 -->
      <div id="资产列表">
        <div class="anthor-info-head">
          <div>
            <el-row :gutter="40">
              <el-col :span="12">
                <i class="el-icon-document" agalin /><span>资产明细</span>
              </el-col>
              <el-col :span="12">
                <div style="float:right">
                  <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleSelectAssets">选择资产</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="anthor-info-body" style="margin:10px">
          <el-table
            :loading="false"
            :data="assetData"
          >
            <el-table-column v-for="column in insideAssetColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
              <template slot-scope="scope">
                <column-render :render="column.render" :row="scope.row" :column="column" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="text" title="删除" size="mini" icon="el-icon-delete" @click.native.prevent="removeAssets(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 备品备件列表 -->
      <div id="备品备件列表">
        <div class="anthor-info-head">
          <div>
            <el-row :gutter="40">
              <el-col :span="12">
                <i class="el-icon-document" agalin /><span>备品备件明细</span>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="anthor-info-body" style="margin:10px">
          <el-table
            :loading="false"
            :data="stockData"
          >
            <el-table-column v-for="column in insideStockColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
              <template slot-scope="scope">
                <column-render :render="column.render" :row="scope.row" :column="column" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 操作按钮 -->
      <el-row :gutter="40">
        <el-col :span="24">
          <div style="float:right">
            <el-button size="mini" type="warning" @click="ok('temporary')">保存</el-button>
            <el-button size="mini" type="primary" @click="ok('submit')">提交</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <!-- 资产 -->
    <SelectDialog title="选择资产" :append-to-body="true" :show="showAddAsset" @on-ok="selectAssetOk" @on-cancel="selectAssetCancel">
      <AssetTable v-if="showAddAsset" ref="assets" :init-query="{s_statusCode: 'using'}" :for-selection="true" />
    </SelectDialog>

    <!-- 知识库 -->
    <ViewDialog title="查询知识库" :append-to-body="true" :show="showKnowledge" @on-cancel="selectKnowledgeCancel">
      <KnowledgeTable v-if="showKnowledge" ref="knowledges" :type="knowledgeType" />
    </ViewDialog>
  </div>
</template>

<script>
import { frontlineProcessingCreate as create, frontlineProcessingDetail as detail } from '@neu/dcom-ui/api/alter'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import ViewDialog from '@neu/biz-core/components/ViewDialog'
import AssetTable from '@neu/dcam-ui/views/fixedAsset/tables'
// import StockTable from '@neu/dcam-ui/views/stock/tables'
import KnowledgeTable from '@neu/dcom-ui/views/knowledge/knowledgeComment/tables'
const formItem = {
  // 工作流TaskId
  taskId: '',
  // 工单号
  workNum: '',
  // 参与一线工程师编码
  helperEngineerCode: '',
  // 参与一线工程师名称
  helperEngineerName: '',
  // 故障级别编码
  failureLevelCode: '',
  // 故障级别名称
  failureLevelName: '',
  // 是否解决
  solved: false,
  // 服务类型编码
  worktypeCode: '',
  // 服务类型名称
  worktypeName: '',
  // 资产信息
  assets: [],
  // 备品备件信息
  stocks: [],
  // 故障解决情况
  failureSolveSituation: '',
  // 状态
  status: 'temporary'
}

const formRules = {
  failureLevelCode: [{ required: true, message: '故障级别不能为空', trigger: 'blur' }],
  worktypeCode: [{ required: true, message: '服务类型不能为空', trigger: 'blur' }],
  solved: [{ required: true, message: '解决情况不能为空', trigger: 'blur' }],
  failureSolveSituation: [{ required: true, message: '故障解决情况不能为空', trigger: 'blur' }]
}

export default {
  name: 'MalfunctionFrontlineProcessingForm',
  components: {
    SelectDialog,
    AssetTable,
    ViewDialog,
    KnowledgeTable
  },
  props: {
    taskId: {
      required: false,
      type: String,
      default: 'NULL'
    },
    workOrderNum: {
      required: false,
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // ----------资产------------------
      showAddAsset: false,
      assetTitle: '新增',
      assetData: [],
      insideAssetColumns: [
        { title: '资产分类', key: 'assetTypeName' },
        { title: '资产编号', key: 'code' },
        { title: '资产名称', key: 'name' },
        { title: '资产条码', key: 'sequence' },
        { title: '规格型号', key: 'productName' }
      ],
      // ----------备品备件------------------
      stockData: [],
      insideStockColumns: [
        {
          title: '货品编号',
          key: 'storckNumber'
        }, {
          title: '备品备件分类',
          key: 'spareTypeName'
        },
        {
          title: '规格型号',
          key: 'specification'
        },
        {
          title: 'SN',
          key: 'sn'
        },
        {
          title: '存放库房',
          key: 'storehouseName'
        },
        {
          title: '单价',
          key: 'unitPrice'
        },
        {
          title: '货品来源',
          key: 'source',
          render: (h, params) => {
            let sourceDesc = ''
            if (params.row.source === 'new') {
              sourceDesc = '合同采购'
            } else if (params.row.source === 'back') {
              sourceDesc = '退库利旧'
            }
            return h('span', [
              h('el-tag', sourceDesc)
            ])
          }
        },
        {
          title: '关联合同',
          key: 'contractName'
        }
      ],
      // 知识库
      showKnowledge: false,
      // 所有的故障级别
      availableFailureLevels: [],
      // 所有服务类型
      availableWorktypes: [],
      // 解决情况下拉框
      availableSolveds: [{ name: '解决', code: true }, { name: '未解决', code: false }],
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: { ...formRules },
      knowledgeType: ''
    }
  },
  created() {
    this.fetch()
    // 故障级别
    findByDictionaryType('failureLevel').then(response => {
      this.availableFailureLevels = response.data
    })
    // 服务类型
    findByDictionaryType('worktype').then(response => {
      this.availableWorktypes = response.data
    })
  },
  methods: {
    fetch() {
      if (this.workOrderNum !== 'NULL') {
        detail(this.workOrderNum, this.taskId).then(response => {
          this.formItem = {
            ...response.data
          }
          // 资产、备件table赋值
          this.assetData = this.formItem.assets
          this.stockData = this.formItem.stocks
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    ok(value) {
      this.$refs.myform.validate((valid) => {
        if (valid) {
          // 赋值工单与任务id
          this.formItem.taskId = this.taskId
          this.formItem.workNum = this.workOrderNum
          // 状态
          this.formItem.status = value
          // 故障级别名称
          const failureLevelName = this.availableFailureLevels.find(e => e.code === this.formItem.failureLevelCode)
          this.formItem.failureLevelName = failureLevelName ? failureLevelName.text : ''
          // 服务类型名称
          const worktypeName = this.availableWorktypes.find(e => e.code === this.formItem.worktypeCode)
          this.formItem.worktypeName = worktypeName ? worktypeName.text : ''
          // 资产列表
          this.formItem.assets = this.assetData
          // 备品备件列表
          this.formItem.stocks = this.stockData
          create(this.formItem).then(res => {
            if (res.status === 'success') {
              this.$emit('cancelNewOrderForm', 'refresh')
            }
          })
        }
      })
    },
    // 知识库
    selectKnowledge() {
      this.knowledgeType = this.formItem.worktypeCode
      this.showKnowledge = true
    },
    // 选择资产
    handleSelectAssets() {
      this.showAddAsset = true
      this.assetTitle = '新增'
    },
    selectAssetOk() {
      const assets = this.$refs.assets.selections
      if (Object.keys(assets).length !== 0) {
        if (this.assetData == null) {
          this.assetData = assets
        } else {
          const assetCodes = this.assetData.map(a => a.code)
          const difference = assets.filter(t => {
            return !assetCodes.includes(t.code)
          })
          this.assetData.push(...difference)
        }
      }
      this.showAddAsset = false
    },
    // 关闭资产
    selectAssetCancel() {
      this.showAddAsset = false
    },
    // 移除资产
    removeAssets(index) {
      this.assetData.splice(index, 1)
    },
    // 关闭知识库
    selectKnowledgeCancel() {
      this.showKnowledge = false
    }

  }
}
</script>
